package com.fm.demo.service

import android.annotation.SuppressLint
import android.app.Service
import android.content.Context
import android.content.Intent
import android.graphics.PixelFormat
import android.os.Binder
import android.os.Build
import android.os.IBinder
import android.util.DisplayMetrics
import android.view.*
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ScreenUtils
import com.blankj.utilcode.util.ShellUtils
import com.fm.common.net.baseCoroutine.runOnUI
import com.fm.demo.R
import com.fm.demo.utils.CommonUtils
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import java.lang.Exception

/**
 * @CreateData:     2020/1/21 10:44
 * @E-Mail:         709674174@qq.com
 * @Author:         lyy
 * @Description:    按钮悬浮窗
 */
class ButtonFloatWindowsService : Service() {
    private val mBinder: MyBinder = MyBinder();
    private var mFloatView: ViewGroup? = null
    private var mWindowManager: WindowManager? = null
    private var mLayoutParams: WindowManager.LayoutParams? = null
    private var mJob: Job? = null

    private var mScreenWidth: Int = 0
    private var mScreenHeight: Int = 0
    private var mScreenDensity: Int = 0

    override fun onBind(intent: Intent): IBinder {
        return mBinder
    }

    @SuppressLint("InflateParams")
    fun createFloatView() {
        if (mWindowManager == null) {
            mLayoutParams = WindowManager.LayoutParams()
            mWindowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
            mWindowManager?.let { windowManager ->
                val metrics = DisplayMetrics()
                windowManager.defaultDisplay.getMetrics(metrics)
                mScreenDensity = metrics.densityDpi
                mScreenWidth = metrics.widthPixels
                mScreenHeight = metrics.heightPixels

                mLayoutParams?.let {
                    it.type = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
                    } else {
                        @Suppress("DEPRECATION")
                        WindowManager.LayoutParams.TYPE_SYSTEM_ALERT
                    }
                    it.format = PixelFormat.RGBA_8888
                    // 设置Window flag
                    it.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                    it.gravity = Gravity.START or Gravity.TOP
                    it.x = mScreenWidth
                    it.y = 100
                    it.width = WindowManager.LayoutParams.WRAP_CONTENT
                    it.height = WindowManager.LayoutParams.WRAP_CONTENT
                }
                mFloatView = LayoutInflater.from(this).inflate(R.layout.button_float_windows_layout, null) as ViewGroup
                mFloatView?.setOnClickListener {
                    mJob?.cancel()
                    mJob = null
                    windowManager.removeViewImmediate(it)
                    CommonUtils.setTopApp(this)
                }
            }
        }
        mWindowManager?.addView(mFloatView, mLayoutParams)
    }

    fun startRefresh(delayTime: Long, intervalTime: Long) {
        val x = ScreenUtils.getScreenWidth() / 2
        val startY = ScreenUtils.getScreenHeight() / 3 * 2
        val endY = ScreenUtils.getScreenHeight() / 4 * 1
        val cmd = "input swipe $x $startY $x $endY"
        mJob = runOnUI {
            delay(delayTime * 1000)
            while (true) {
                val shellResult = ShellUtils.execCmd(cmd, true)
                LogUtils.e("shell run result : ", shellResult.toString())
                delay(intervalTime * 1000)
            }
        }
    }


    inner class MyBinder : Binder() {
        fun getService(): ButtonFloatWindowsService {
            return this@ButtonFloatWindowsService
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (mFloatView != null) {
            try {
                mWindowManager?.removeView(mFloatView)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
}